#### Figure S12: Norm support by affpol (LOESS) ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(srvyr)
# library(ggthemes)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

cs_affpolre_loess = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> # Just D/R
  select(affpol, all_of(norm_indc), weight) |>
  pivot_longer(-c("affpol","weight"), names_to = "var", values_to = "val") |> 
  mutate(var = recode_factor(var,
                             norm_pollingc = "Polling Stations",
                             norm_loyaltyc = "Loyalty",
                             norm_judgesc = "Ignore Courts",
                             norm_executivec = "Exec. Power",
                             norm_censorshipc = "Censorship"))

terc_plot = \(data, x){
  data |> 
    filter(var == x) |>
    filter(!is.na(val)) |> 
    ggplot(aes(x = affpol, y = val)) +
    geom_smooth(aes(weight = weight)) +
    scale_y_continuous(breaks = c(1,3,5), limits = c(1,5),
                       labels = c("Strongly\noppose","Neither\nsupport\nnor oppose","Strongly\nsupport")) +
    labs(x = "Affective Polarization", y = "Norm Violation Support",
         subtitle = x) +
    lims(x = c(-100,100)) +
    theme_prl()
}

p_polling = terc_plot(cs_affpolre_loess, "Polling Stations")
p_loyalty = terc_plot(cs_affpolre_loess, "Loyalty")
p_courts = terc_plot(cs_affpolre_loess, "Ignore Courts")
p_censor = terc_plot(cs_affpolre_loess, "Censorship")

fig_s12 = ((p_polling + p_loyalty) / (p_courts + p_censor))

print(fig_s12)

ggsave(here("Plots","Supplementary","figure_s12.pdf"),
       fig_s12,
       units = "in",
       width = 7, height = 6,
       dpi = 600)

rm(cs_affpolre_loess)